package com.foreveross.webbase.book.web;



import java.io.File;
import java.util.UUID;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.foreveross.webbase.book.entity.Book;
import com.foreveross.webbase.book.service.BookService;
import com.foreveross.webbase.common.config.Global;
import com.foreveross.webbase.common.persistence.Page;
import com.foreveross.webbase.common.utils.FileUtils;
import com.foreveross.webbase.common.utils.StringUtils;
import com.foreveross.webbase.common.web.BaseController;

@Controller
@RequestMapping(value = "${adminPath}/book")
public class BookController  extends BaseController {

	@Autowired
	private BookService bookService;
	
	@RequestMapping(value = {"list", ""})
	public String list(Book book) {
		Page<Book> page = bookService.findPage(new Page<Book>(request(), response()), book); 
		attr("page", page);
		return "book/book-list";
	}

	@RequestMapping("form")
	public String form(String id) {
		if(StringUtils.isNotEmpty(id)) {
			Book book=bookService.get(id);
			attr("book", book);
		} else {
			attr("book", new Book());
		}
		return "book/book-form";
	}

	@RequestMapping("save")
	public String save(MultipartFile file,Book book,RedirectAttributes redirectAttributes) {
		//getOriginalFilename获取文件的完整名字
		book.setBookpicture(file.getOriginalFilename());
		//getFileExtension获取文件扩展名
		book.setExt(FileUtils.getFileExtension(file.getOriginalFilename()));
		String path=UUID.randomUUID().toString();
		String uploaddir=Global.getConfig("file.uploaddir");
		String filepath=uploaddir+path+"."+book.getExt();
		File f=new File(filepath);
		try {
//			if(book.getIsNewRecord()) {
//				book.setCreatetime(new Date());
//			}
			file.transferTo(f);
			book.setPath(path+"."+book.getExt()); //相对路径
			bookService.save(book);
			addMessage(redirectAttributes, "保存Book123成功");
		} catch (Exception e) {
			addMessage(redirectAttributes, "保存Book失败");
		}
		
		return "redirect:"+Global.getAdminPath()+"/book/?repage";
	}
	
	@RequestMapping("delete")
	public String delete(@RequestParam String id, RedirectAttributes redirectAttributes) {
		
		bookService.delete(id);
		addMessage(redirectAttributes, "删除Book成功");
		return "redirect:"+Global.getAdminPath()+"/book/?repage";
	}

@RequestMapping("download")
public void download(String id,HttpServletResponse resp) {
	
	Book book=bookService.get(id);
	String uploaddir=Global.getConfig("file.uploaddir");
	File f=new File(uploaddir,book.getPath());
	
	resp.setContentType("application/force-download");
	FileUtils.downFile(f, request(), resp, book.getBookpicture());
}
}